package br.com.gestantes.controle;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Locale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import br.com.gestantes.modelo.Estoque;
import br.com.gestantes.modelo.serraria.PedidoSerraria;


@Controller
public class GerenteController {

	private static final Logger logger = LoggerFactory.getLogger(GerenteController.class);

	@RequestMapping("/gerente/serraria")
	public String home(Locale locale, Model model) {

		logger.info("Gerente Controller.");

		Estoque estoque = new Estoque();

		model.addAttribute("produtos", estoque.produtos);
		

		model.addAttribute("pedido", new PedidoSerraria());

		return "gerente/serraria";
	}

	@RequestMapping(value = "gerente/incluiPedido", method = RequestMethod.POST)
	public String incluiPedido(@ModelAttribute("pedido") PedidoSerraria pedido, BindingResult result){

		Connection con = null;
		PreparedStatement pst = null;

		String driver = "org.postgresql.Driver";
		String url = "jdbc:postgresql://localhost:5432/gestantes";
		String user = "root";
		String password = "123";

		try {

			Class.forName(driver).newInstance();
			con = DriverManager.getConnection(url, user, password);

			String query = "INSERT INTO PEDIDOS_SERRARIA(ped_serr_sq_usuario, ped_serr_sq_item, ped_serr_int_qtd, ped_serr_dt_data, ped_serr_enum_status) VALUES(?, ?, ?, now(), 'Novo')";

			pst = con.prepareStatement(query);
			pst.setInt(1, pedido.getIdUsuario());
			pst.setInt(2, pedido.getIdItem());
			pst.setInt(3, pedido.getQuantidade());
			pst.executeUpdate();

		} catch (SQLException ex) {

			ex.printStackTrace();

		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {

				if (pst != null) {
					pst.close();
				}
				if (con != null) {
					con.close();
				}

			} catch (SQLException ex) {
				ex.printStackTrace();
			}
		}

		return "gerente/serraria";
	}

}
